-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSolution.java
More file actions
28 lines (23 loc) · 824 Bytes
/
Solution.java
File metadata and controls
28 lines (23 loc) · 824 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import java.util.Scanner;
public class StringCompression {
public static String compressString(String str) {
StringBuilder compressed = new StringBuilder();
int count = 1;
for (int i = 0; i < str.length(); i++) {
if (i < str.length() - 1 && str.charAt(i) == str.charAt(i + 1)) {
count++;
} else {
compressed.append(str.charAt(i)).append(count);
count = 1;
}
}
return compressed.toString();
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String str = scanner.nextLine();
String result = compressString(str);
System.out.println("Compressed string: " + result);
}
}